#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/5/16 16:44
@Author  : HZP
@File    : 2.文件对话消息历史组件实现记忆.py
"""
from dotenv import load_dotenv
from langchain_community.chat_message_histories import FileChatMessageHistory
from openai import OpenAI

load_dotenv()
message_history = FileChatMessageHistory("./memory.txt")
llm = OpenAI(base_url="https://api-wc33k5m6j8f4ve1d.aistudio-app.com/v1")
print(message_history)
while True:
    #1、用户输入问题
    query = input("Human：")
    #2、终止聊天对话
    if query=="q":
        break
    #3、prompt提示语的构造
    prompt = ("你是中电三公司聊天机器人，可以根据相应的上下文回复用户信息，上下文里存放的是人类与你对话的信息列表。\n\n"
              f"<context>{message_history}</context>\n\n")
    #4、调用llm模型进行回答
    response = llm.chat.completions.create( model="deepseek-r1:70b",stream=True,
                                           messages=[
                                               {"role": "system", "content": prompt},
                                               {"role": "user", "content": query},
                                           ])
    #5、进行聊天对答
    print("AI：",flush=True, end="")
    ai_content=""
    for chunk in response:
        content =chunk.choices[0].delta.content
        print(content, flush=True, end="")
        if content is None:
            break
        ai_content += content
    #6、将用户和机器人的对话记录到文件中
    message_history.add_user_message(query)
    message_history.add_ai_message(ai_content)
